<template>
  <div>
    <h2>购物车管理</h2>
    <el-card>
      <div style="margin-bottom: 16px;">
        <el-button type="danger" @click="handleBatchRemove" :disabled="!multipleSelection.length">批量删除</el-button>
        <el-button @click="handleClear" style="margin-left: 8px;">清空购物车</el-button>
      </div>
      <el-table
        :data="cartList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="productName" label="商品名" />
        <el-table-column prop="productImage" label="图片" width="60">
          <template #default="scope">
            <el-image v-if="scope.row.productImage" :src="scope.row.productImage" style="width:40px;height:40px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="productPrice" label="单价" width="100" />
        <el-table-column prop="quantity" label="数量" width="100">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              @change="val => handleQuantityChange(scope.row, val)"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="checked" label="选中" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.checked"
              @change="val => handleCheckedChange(scope.row, val)"
              :active-value="true"
              :inactive-value="false"
            />
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="小计" width="100" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleRemove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <span>总金额：<b>{{ totalAmount }}</b></span>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  getAdminCartList,
  updateAdminCart,
  deleteAdminCart
} from '../api/cart'
import { getAdminProductDetail } from '../api/product'
import { ElMessage, ElMessageBox } from 'element-plus'

const cartList = ref([])
const multipleSelection = ref([])
const totalAmount = ref(0)

const fetchList = async () => {
  try {
    const res = await getAdminCartList()
    if (res.data) {
      // 批量补充商品信息
      const carts = res.data
      const detailPromises = carts.map(cart =>
        getAdminProductDetail(cart.productId).then(pr => ({
          ...cart,
          productName: pr.data?.name || '',
          productPrice: pr.data?.price || 0,
          productImage: pr.data?.mainImage || ''
        }))
      )
      cartList.value = await Promise.all(detailPromises)
      totalAmount.value = cartList.value.reduce((sum, item) => sum + (item.quantity * (item.productPrice || 0)), 0)
    }
  } catch (e) {
    ElMessage.error('获取购物车失败')
  }
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleQuantityChange = async (row, val) => {
  try {
    await updateCartQuantity({ cartId: row.id, quantity: val })
    ElMessage.success('数量已更新')
    fetchList()
  } catch (e) {
    ElMessage.error('更新数量失败')
  }
}

const handleCheckedChange = async (row, val) => {
  try {
    await updateCartChecked({ cartId: row.id, checked: val })
    ElMessage.success('状态已更新')
    fetchList()
  } catch (e) {
    ElMessage.error('更新状态失败')
  }
}

const handleRemove = (row) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', { type: 'warning' })
    .then(async () => {
      await removeFromCart(row.id)
      ElMessage.success('已删除')
      fetchList()
    })
    .catch(() => {})
}

const handleBatchRemove = () => {
  if (!multipleSelection.value.length) return
  const ids = multipleSelection.value.map(item => item.id)
  ElMessageBox.confirm('确定要批量删除选中商品吗？', '警告', { type: 'error' })
    .then(async () => {
      await batchRemoveFromCart(ids)
      ElMessage.success('批量删除成功')
      fetchList()
    })
    .catch(() => {})
}

const handleClear = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '警告', { type: 'error' })
    .then(async () => {
      await clearCart()
      ElMessage.success('购物车已清空')
      fetchList()
    })
    .catch(() => {})
}

onMounted(() => {
  fetchList()
})
</script>